package com.credithc.customers.manager.service.impl;

import com.credithc.baseserv.pageHelper.PageInfo;
import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.base.factory.DictionaryFactory;
import com.credithc.customers.base.mapper.ProductInfoStatisticMapper;
import com.credithc.customers.base.po.CustomerProductInfoPo;
import com.credithc.customers.base.utils.CustomerUtils;
import com.credithc.customers.manager.echarts.CustomerProductStatsPie;
import com.credithc.customers.manager.mapper.CustomerProductInfoMapper;
import com.credithc.customers.manager.mapper.EChartsMapper;
import com.credithc.customers.manager.po.CustomerProductPiePo;
import com.credithc.customers.manager.ro.CustomerProductInfoRo;
import com.credithc.customers.manager.service.CustomerProductService;
import com.credithc.customers.manager.utils.StatsUtils;
import com.credithc.customers.manager.vo.CustomerProductVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhukai
 * @date 2019/1/22 16:45
 */
@Service
public class CustomerProductServiceImpl implements CustomerProductService {

    @Autowired
    private CustomerProductInfoMapper customerProductInfoMapper;

    @Autowired
    private EChartsMapper eChartsMapper;

    @Autowired
    private ProductInfoStatisticMapper productInfoStatisticMapper;


    @Override
    public PageInfo<CustomerProductVo> getList(CustomerProductInfoRo ro, Integer pageNo, Integer pageSize) {
        List<CustomerProductVo> vos = new ArrayList<>();
        List<CustomerProductInfoPo> pos = new ArrayList<>();
        int count = 0;
        //如果查询只包括或含产品类型，产品状态，归属平台和时间则走以下下查询
        if (StringUtils.isBlank(ro.getCustomerNo()) && StringUtils.isBlank(ro.getCustomerName()) && StringUtils.isBlank(ro.getProductNo())) {
            String createTimeStart = ro.getCreateTimeStart();
            String createTimeEnd = ro.getCreateTimeEnd();
            if (StringUtils.isBlank(ro.getCreateTimeEnd())){
                //未选取结束时间
                createTimeEnd = StatsUtils.getCurrentTime().substring(0, 10);
            }
            int countEndDay;
            String countStartSum = "0";
            String nextDate = StatsUtils.getPostDate(1, createTimeEnd);
            String endDate = StatsUtils.getPastDate(1, createTimeEnd.substring(0, 10));
            if (ro.getProductSourceSystem() == null || ro.getProductSourceSystem() == "") {
                ro.setProductSourceSystem(null);
            }
            if (ro.getProductType() == null || ro.getProductType() == "") {
                ro.setProductType(null);
            }
            if (StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                countEndDay = 0;
            } else {
                //countEndDay = productInfoStatisticMapper.getTodaySumByAll(ro.getProductSourceSystem(),ro.getProductType(),ro.getProductStatus(), nextDate, createTimeEnd);
                countEndDay = 0;
            }
            if (StringUtils.isNotBlank(ro.getCreateTimeStart())) {
                String startDate = StatsUtils.getPastDate(1, createTimeStart.substring(0, 10));
                countStartSum = productInfoStatisticMapper.getPastSum(ro.getProductSourceSystem(),ro.getProductType(),ro.getProductStatus(), startDate);
            }
            String countEndSum = productInfoStatisticMapper.getPastSum(ro.getProductSourceSystem(),ro.getProductType(),ro.getProductStatus(), endDate);
            if (countEndSum == null) {
                countEndSum = "0";
            }
            if (countStartSum == null) {
                countStartSum = "0";
            }
            //如果没选择开始时间和结束时间则把时间为空的数据给补上
            String countTimeNull = "0";
            if (StringUtils.isBlank(ro.getCreateTimeStart()) && StringUtils.isBlank(ro.getCreateTimeEnd())){
                countTimeNull  = productInfoStatisticMapper.getPastSum(ro.getProductSourceSystem(),ro.getProductType(),ro.getProductStatus(), "0000-00-00");
            }
            if (countTimeNull == null) {
                countTimeNull = "0";
            }
            count = Integer.parseInt(countEndSum) + countEndDay + Integer.parseInt(countTimeNull) - Integer.parseInt(countStartSum);
            Integer startPage = (pageNo - 1) * pageSize;
            pos = customerProductInfoMapper.getListByPage(ro,startPage,pageSize);
        }else{
            Page<CustomerProductInfoPo> page = PageHelper.startPage(pageNo, pageSize);
            pos = customerProductInfoMapper.getList(ro);
            count = (int) page.getTotal();
        }
        CustomerProductVo vo;
        for (CustomerProductInfoPo po : pos) {
            vo = new CustomerProductVo();
            BeanUtils.copyProperties(po, vo);
            vo.setCreateTime(CustomerUtils.timestamp2Stirng(po.getCreateTime()));
            vo.setUpdateTime(CustomerUtils.timestamp2Stirng(po.getUpdateTime()));
            vo.setProductStartTime(CustomerUtils.timestamp2Stirng(po.getProductStartTime()));
            vo.setProductEndTime(CustomerUtils.timestamp2Stirng(po.getProductEndTime()));
            vo.setProductStatusStr(getProductStatusStr(String.valueOf(po.getProductStatus())));
            vo.setProductTypeStr(getProductTypeStr(po.getProductType()));
            vo.setProductSourceSystemStr(getProductChannelStr(po.getProductSourceSystem()));
            vos.add(vo);
        }
        return new PageInfo(vos, count, pageNo, pageSize);
    }

    @Override
    public String getProduct(String customerNo, String statsType) {
        String startTime = null;
        String endTime = null;
        String currentDay = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        if ("week".equals(statsType)) {
            startTime = StatsUtils.getPastDate(6, currentDay);
            endTime = StatsUtils.getPostDate(1,currentDay);
        } else if ("month".equals(statsType)) {
            startTime = StatsUtils.getPastDate(29, currentDay);
            endTime = StatsUtils.getPostDate(1,currentDay);
        }
        List<CustomerProductPiePo> pos;
        if (customerNo.startsWith(CustomerConstants.PRE_CUSTOMER_PREFIX)) {
            pos = eChartsMapper.statsCustomerProduct(customerNo, startTime, endTime, "yes");
        } else {
            pos = eChartsMapper.statsCustomerProduct(customerNo, startTime, endTime, null);
        }
        List<String> colList = new ArrayList<>();
        for (CustomerProductPiePo po : pos) {
            colList.add(po.getProductType());
        }
        CustomerProductStatsPie pie = new CustomerProductStatsPie(pos, colList);
        return pie.generateGraph();
    }

    @Override
    public PageInfo<CustomerProductVo> listByPreCustomerNo(String customerNo, Integer pageNo, Integer pageSize) {
        if (StringUtils.isBlank(customerNo)) {
            return null;
        }

        Example example = new Example(CustomerProductInfoPo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("customerNo", customerNo);
        example.setDistinct(Boolean.FALSE);
        example.setOrderByClause("product_start_time DESC");

        Page<CustomerProductVo> page = PageHelper.startPage(pageNo, pageSize);
        List<CustomerProductInfoPo> infoPos = customerProductInfoMapper.selectByExample(example);

        Long total = page.getTotal();
        List<CustomerProductVo> vos = infoPos.parallelStream().map(po -> convertPoToVo(po)).collect(Collectors.toList());
        return new PageInfo(vos, total.intValue(), pageNo, pageSize);
    }

    private CustomerProductVo convertPoToVo(CustomerProductInfoPo po) {
        CustomerProductVo vo = new CustomerProductVo();
        BeanUtils.copyProperties(po, vo);
        vo.setCreateTime(CustomerUtils.timestamp2Stirng(po.getCreateTime()));
        vo.setUpdateTime(CustomerUtils.timestamp2Stirng(po.getUpdateTime()));
        vo.setProductStartTime(CustomerUtils.timestamp2Stirng(po.getProductStartTime()));
        vo.setProductEndTime(CustomerUtils.timestamp2Stirng(po.getProductEndTime()));
        vo.setProductStatusStr(getProductStatusStr(String.valueOf(po.getProductStatus())));
        vo.setProductTypeStr(getProductTypeStr(po.getProductType()));
        vo.setProductSourceSystemStr(getProductChannelStr(po.getProductSourceSystem()));
        return vo;
    }

    private String getProductStatusStr(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        Map<String, String> contactTypeMap = DictionaryFactory.Dict.PRODUCT_STATUS.getDictMap();
        return contactTypeMap.get(key);
    }

    private String getProductTypeStr(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        Map<String, String> contactTypeMap = DictionaryFactory.Dict.PRODUCT_TYPE.getDictMap();
        return contactTypeMap.get(key);
    }

    private String getProductChannelStr(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        Map<String, String> contactTypeMap = DictionaryFactory.Dict.PRODUCT_CHANNEL.getDictMap();
        return contactTypeMap.get(key);
    }


    @Override
    public List<CustomerProductVo> getListDetail(String customerNo) {
        CustomerProductInfoRo ro = new CustomerProductInfoRo();
        ro.setCustomerNo(customerNo);
        List<CustomerProductInfoPo> pos = customerProductInfoMapper.getList(ro);
        List<CustomerProductVo> vos = new ArrayList<>();
        CustomerProductVo vo;
        for (CustomerProductInfoPo po : pos) {
            vo = new CustomerProductVo();
            BeanUtils.copyProperties(po, vo);
            vo.setCreateTime(CustomerUtils.timestamp2Stirng(po.getCreateTime()));
            vo.setUpdateTime(CustomerUtils.timestamp2Stirng(po.getUpdateTime()));
            vo.setProductStartTime(CustomerUtils.timestamp2Stirng(po.getProductStartTime()));
            vo.setProductEndTime(CustomerUtils.timestamp2Stirng(po.getProductEndTime()));
            vo.setProductStatusStr(getProductStatusStr(String.valueOf(po.getProductStatus())));
            vo.setProductTypeStr(getProductTypeStr(po.getProductType()));
            vo.setProductSourceSystemStr(getProductChannelStr(po.getProductSourceSystem()));
            vos.add(vo);
        }
        return vos;
    }
}
